#!/usr/bin/env python
# coding: utf-8

# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
#from django.views.generic import DetailView, ListView, CreateView, UpdateView
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse
from django.utils.decorators import method_decorator
from authfuncs import get_user_profile, auth_user_required
from django.core.context_processors import csrf
from django.contrib import messages
from datetime import datetime
from django.db.models import Q
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.contrib import messages

def menu_element(url, name, title=u'', right = False, **kwargs):
    def get_url(url):
        #return reverse(url)
        try: return reverse(url)
        except: return url

    return {'url': get_url(url), 'name': name, 'title': title, 'right': right, 'submenu': kwargs.get('submenu', [])}


def get_default_context(request):
    c = {}
    c.update(csrf(request))
    c['messages'] = messages.get_messages(request)
    
    unblog_submenu = [
        menu_element('unblog_topic_list', u'Темы', u'Список тем для разговора'),
    ]
    menu = [
        menu_element('home', u'Главная', u'Веб-клиент для Тоже Мне Радио'),
        menu_element('tmsearch', u'Поиск музыки', u'Поисковик по базе музыки Тоже Мне Радио'),
        menu_element('unblog', u'Записки', u'Про все остальное', submenu = unblog_submenu),
        menu_element('tmp_view', u'Опыты', u'Тут все может не работать!'),
        # menu_element('/admin', u'Админка', U'Не для всех', True),
    ]
    user = request.user if request.user.is_authenticated() else None
    profile = get_user_profile(request)
    if not profile:
        pass
        #menu.append( menu_element('login', 'Войти', True) )
    c['request'] = request
    c['main_menu'] = menu
    if user:
        c['user'] = user
        c['user_profile'] = profile

    return c

def login_variants(request):
    if request.user.is_authenticated(): return HttpResponseRedirect('/')
    c = get_default_context(request)
    return render_to_response('login_variants.html', c)

@auth_user_required
def profile_edit(request, **kwargs):
    from forms import UserInfoForm
    profile = kwargs['profile']
    c = get_default_context(request)
    c['title'] = u'Профиль пользователя'
    data = {'first_name': profile.user.first_name,
            'last_name': profile.user.last_name,
            'email': profile.user.email,
            'nickname': profile.nickname,
            'jabber': profile.jabber,
            'tm_token': profile.tm_token,
            'show_avatar': profile.show_avatar}
    form = UserInfoForm(data)
    if request.method == 'POST':
        form = UserInfoForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            profile.user.first_name = data['first_name']
            profile.user.last_name = data['last_name']
            profile.user.email = data['email']
            profile.nickname = data['nickname']
            profile.jabber = data['jabber']
            profile.show_avatar = data['show_avatar']
            profile.tm_token = data['tm_token']
            profile.user.save()
            profile.save()
            messages.success(request, u'Данные профиля успешно сохранены.')
            return HttpResponseRedirect("/")
        else:
            pass
    c['form'] = form

    return render_to_response('userinfo.html', c)

def light_view(request):
    c = get_default_context(request)
    return render_to_response('tmradio_light.html', c)

def tmp_view(request):
    c = get_default_context(request)
    return render_to_response('tmp_view.html', c)